﻿using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;

/// <summary>
/// RDM 文件导入器 - 直接将 RDM 文件识别为 Mesh 资产
/// </summary>
[ScriptedImporter(1, "rdm")]
public class RDMAssetImporter : ScriptedImporter
{
    // 导入设置类
    [Serializable]
    public class RDMImportSettings
    {
        public string positionColumn = "_input0";
        public string normalColumn = "_input1";
        public string uvColumn = "_input3";
        public string colorColumn = "None";  // 颜色列设置，默认不读取
        public string uv2Column = "None";    // UV2列设置，默认不读取
        public bool generateTangents = true;      // 自动生成切线
        public bool calculateNormals = false;     // 自动计算法线
        public bool flipUVY = true;               // 翻转UV的Y轴
        public bool invertNormals = false;        // 反转法线方向
        public bool reverseWinding = false;       // 反转三角形顶点顺序
        public bool reverseVertexIndices = false; // 反转顶点索引顺序
        public bool calculateSmoothNormals = true; // 计算平滑法线
        public float smoothAngleThreshold = 60.0f; // 平滑角度阈值(度)
        public bool autoRemapIndices = true;       // 自动重映射索引，使最小索引为0
        public bool maxThan65536 = true;
    }

    [SerializeField]
    private RDMImportSettings importSettings = new RDMImportSettings();

    public override void OnImportAsset(AssetImportContext ctx)
    {
        try
        {
            Debug.Log($"开始导入 RDM 文件: {ctx.assetPath}");

            // 读取 RDM 文件数据
            RDMData data = ReadRDMFile(ctx.assetPath, importSettings, ctx);
            if (data == null)
            {
                ctx.LogImportError("无法解析RDM文件数据");
                return;
            }

            // 验证数据完整性
            if (!ValidateRDMData(data, ctx))
            {
                return;
            }

            // 自动重映射索引，确保从0开始
            if (importSettings.autoRemapIndices)
            {
                RemapIndices(data);
                Debug.Log("已自动重映射顶点索引，确保从0开始");
            }

            // 修复UV Y轴反转问题
            if (importSettings.flipUVY)
            {
                FlipUVY(data.UVs);
                Debug.Log("已翻转UV的Y轴");
            }

            // 如果需要反转法线方向
            if (importSettings.invertNormals)
            {
                InvertNormals(data.Normals);
                Debug.Log("已反转法线方向");
            }

            // 如果需要反转三角形顶点顺序
            if (importSettings.reverseWinding)
            {
                ReverseWindingOrder(data.Triangles);
                Debug.Log("已反转三角形顶点顺序");
            }

            // 创建 Mesh 对象
            Mesh mesh = CreateMeshFromRDMData(data, importSettings);
            if (mesh == null)
            {
                ctx.LogImportError("创建Mesh失败");
                return;
            }

            // 如果需要反转顶点索引
            if (importSettings.reverseVertexIndices)
            {
                ReverseVertexIndices(mesh);
            }

            // 如果需要计算平滑法线
            if (importSettings.calculateSmoothNormals)
            {
                CalculateSmoothNormals(mesh, importSettings.smoothAngleThreshold);
                Debug.Log("已计算平滑法线");
            }

            // 设置网格名称
            mesh.name = Path.GetFileNameWithoutExtension(ctx.assetPath);

            // 将Mesh添加到导入上下文中
            ctx.AddObjectToAsset("mesh", mesh);
            ctx.SetMainObject(mesh);

            Debug.Log($"成功导入 RDM 文件为 Mesh: {ctx.assetPath}");
        }
        catch (Exception ex)
        {
            ctx.LogImportError($"导入 RDM 文件时出错: {ex.Message}\n{ex.StackTrace}");
        }
    }

    // 读取 RDM 文件数据
    private RDMData ReadRDMFile(string filePath, RDMImportSettings settings, AssetImportContext ctx)
    {
        try
        {
            string[] lines = File.ReadAllLines(filePath);
            if (lines.Length < 2)
            {
                ctx.LogImportError($"RDM 文件数据不足: {filePath}");
                return null;
            }

            // 解析表头
            string[] headers = lines[0].Split(',');
            if (headers.Length == 0)
            {
                ctx.LogImportError($"RDM 文件格式无效: 未找到表头 - {filePath}");
                return null;
            }

            // 收集可用列
            List<string> availableColumns = new List<string>();
            for (int i = 0; i < headers.Length; i++)
            {
                string header = headers[i].Trim();
                if (!string.IsNullOrEmpty(header))
                    availableColumns.Add(header);
            }

            // 检查是否有足够的数据列
            if (availableColumns.Count < 3)
            {
                ctx.LogImportError($"RDM 文件列数不足: {filePath}");
                return null;
            }

            // 解析数据行
            List<Vector3> vertices = new List<Vector3>();
            List<Vector3> normals = new List<Vector3>();
            List<Vector2> uvs = new List<Vector2>();
            List<Vector2> uv2s = new List<Vector2>();
            List<Color> colors = new List<Color>();
            List<int> rawIndices = new List<int>(); // 存储原始索引
            List<int> triangles = new List<int>();

            // 找出IDX列的位置
            int idxColumnIndex = -1;
            for (int i = 0; i < headers.Length; i++)
            {
                if (headers[i].Trim().Equals("IDX", StringComparison.OrdinalIgnoreCase))
                {
                    idxColumnIndex = i;
                    break;
                }
            }

            if (idxColumnIndex == -1)
            {
                ctx.LogImportError($"RDM 文件中未找到 IDX 列: {filePath}");
                return null;
            }

            // 统计解析错误
            int vertexParseErrors = 0;
            int normalParseErrors = 0;
            int uvParseErrors = 0;
            int colorParseErrors = 0;
            int uv2ParseErrors = 0;
            int invalidLineCount = 0;

            for (int i = 1; i < lines.Length; i++)
            {
                string[] values = lines[i].Split(',');
                if (values.Length < headers.Length)
                {
                    invalidLineCount++;
                    continue;
                }

                // 解析顶点索引 (IDX)
                if (!int.TryParse(values[idxColumnIndex].Trim(), out int vertexIndex))
                {
                    vertexParseErrors++;
                    continue;
                }

                rawIndices.Add(vertexIndex); // 保存原始索引

                // 确保列表大小足够
                while (vertices.Count <= vertexIndex)
                {
                    vertices.Add(Vector3.zero);
                    normals.Add(Vector3.zero);
                    uvs.Add(Vector2.zero);
                    uv2s.Add(Vector2.zero);
                    colors.Add(Color.white);
                }

                // 解析位置
                bool positionParsed = TryParseVector3(values, headers, settings.positionColumn, out Vector3 position);
                if (positionParsed)
                    vertices[vertexIndex] = position;
                else
                    vertexParseErrors++;

                // 解析法线
                bool normalParsed = TryParseVector3(values, headers, settings.normalColumn, out Vector3 normal);
                if (normalParsed)
                {
                    normals[vertexIndex] = normal.normalized;
                }
                else
                {
                    normalParseErrors++;
                    // 如果法线解析失败，使用默认值
                    normals[vertexIndex] = Vector3.up;
                }

                // 解析UV
                bool uvParsed = TryParseVector2(values, headers, settings.uvColumn, out Vector2 uv);
                

                if (uvParsed)
                {
                    uv.x = 1f - uv.x;
                    //uv.y = 1f - uv.y;
                    uvs[vertexIndex] = uv;
                }
                else
                {
                    uvParseErrors++;
                    // 如果UV解析失败，使用默认值
                    uvs[vertexIndex] = Vector2.zero;
                }

                // 解析颜色
                if (!string.IsNullOrEmpty(settings.colorColumn) && settings.colorColumn != "None")
                {
                    bool colorParsed = TryParseColor(values, headers, settings.colorColumn, out Color color);
                    if (colorParsed)
                    {
                        colors[vertexIndex] = color;
                    }
                    else
                    {
                        colorParseErrors++;
                        // 如果颜色解析失败，使用默认值
                        colors[vertexIndex] = Color.white;
                    }
                }

                // 解析UV2
                if (!string.IsNullOrEmpty(settings.uv2Column) && settings.uv2Column != "None")
                {
                    bool uv2Parsed = TryParseVector2(values, headers, settings.uv2Column, out Vector2 uv2);
                    if (uv2Parsed)
                    {
                        uv2s[vertexIndex] = uv2;
                    }
                    else
                    {
                        uv2ParseErrors++;
                        // 如果UV2解析失败，使用默认值
                        uv2s[vertexIndex] = Vector2.zero;
                    }
                }
            }

            // 记录解析统计信息
            if (vertexParseErrors > 0)
                Debug.LogWarning($"顶点解析错误: {vertexParseErrors} 处");
            if (normalParseErrors > 0)
                Debug.LogWarning($"法线解析错误: {normalParseErrors} 处");
            if (uvParseErrors > 0)
                Debug.LogWarning($"UV解析错误: {uvParseErrors} 处");
            if (colorParseErrors > 0)
                Debug.LogWarning($"颜色解析错误: {colorParseErrors} 处");
            if (uv2ParseErrors > 0)
                Debug.LogWarning($"UV2解析错误: {uv2ParseErrors} 处");
            if (invalidLineCount > 0)
                Debug.LogWarning($"无效行数: {invalidLineCount} 行");

            // 创建三角形索引 (假设每3行构成一个三角形)
            int invalidTriangleCount = 0;
            for (int i = 1; i < lines.Length; i += 3)
            {
                if (i + 2 < lines.Length)
                {
                    string[] line1 = lines[i].Split(',');
                    string[] line2 = lines[i + 1].Split(',');
                    string[] line3 = lines[i + 2].Split(',');

                    if (line1.Length > idxColumnIndex && line2.Length > idxColumnIndex && line3.Length > idxColumnIndex)
                    {
                        if (!int.TryParse(line1[idxColumnIndex].Trim(), out int idx1) ||
                            !int.TryParse(line2[idxColumnIndex].Trim(), out int idx2) ||
                            !int.TryParse(line3[idxColumnIndex].Trim(), out int idx3))
                        {
                            invalidTriangleCount++;
                            continue;
                        }

                        // 确保索引有效
                        if (idx1 < vertices.Count && idx2 < vertices.Count && idx3 < vertices.Count)
                        {
                            triangles.Add(idx1);
                            triangles.Add(idx2);
                            triangles.Add(idx3);
                        }
                        else
                        {
                            invalidTriangleCount++;
                        }
                    }
                    else
                    {
                        invalidTriangleCount++;
                    }
                }
                else
                {
                    invalidTriangleCount++;
                }
            }

            if (invalidTriangleCount > 0)
                Debug.LogWarning($"无效三角形: {invalidTriangleCount} 个");

            Debug.Log($"解析结果: 顶点={vertices.Count}, 法线={normals.Count}, UV={uvs.Count}, " +
                      $"颜色={colors.Count}, UV2={uv2s.Count}, 三角形={triangles.Count / 3}");

            return new RDMData
            {
                Vertices = vertices.ToArray(),
                Normals = normals.ToArray(),
                UVs = uvs.ToArray(),
                UV2s = uv2s.ToArray(),
                Colors = colors.ToArray(),
                Triangles = triangles.ToArray(),
                RawIndices = rawIndices.ToArray() // 新增原始索引数组
            };
        }
        catch (Exception ex)
        {
            ctx.LogImportError($"读取 RDM 文件时出错: {filePath}\n错误: {ex.Message}\n{ex.StackTrace}");
            return null;
        }
    }

    // 新增：自动重映射顶点索引
    private void RemapIndices(RDMData data)
    {
        if (data.RawIndices == null || data.RawIndices.Length == 0)
            return;

        // 找到最小索引值
        int minIndex = int.MaxValue;
        foreach (int index in data.RawIndices)
        {
            if (index < minIndex)
                minIndex = index;
        }

        // 如果最小索引已经是0，不需要重映射
        if (minIndex == 0)
            return;

        // 创建索引映射表
        Dictionary<int, int> indexMap = new Dictionary<int, int>();
        int newIndex = 0;

        // 为每个唯一的原始索引分配新索引
        foreach (int index in data.RawIndices)
        {
            if (!indexMap.ContainsKey(index))
            {
                indexMap[index] = newIndex++;
            }
        }

        // 重映射顶点数据
        List<Vector3> newVertices = new List<Vector3>(indexMap.Count);
        List<Vector3> newNormals = new List<Vector3>(indexMap.Count);
        List<Vector2> newUVs = new List<Vector2>(indexMap.Count);
        List<Vector2> newUV2s = new List<Vector2>(indexMap.Count);
        List<Color> newColors = new List<Color>(indexMap.Count);

        foreach (var pair in indexMap)
        {
            int originalIndex = pair.Key;
            int newIndexValue = pair.Value;

            newVertices.Add(data.Vertices[originalIndex]);
            newNormals.Add(data.Normals[originalIndex]);
            newUVs.Add(data.UVs[originalIndex]);
            newUV2s.Add(data.UV2s[originalIndex]);
            newColors.Add(data.Colors[originalIndex]);
        }

        // 重映射三角形索引
        List<int> newTriangles = new List<int>(data.Triangles.Length);
        foreach (int index in data.Triangles)
        {
            if (indexMap.TryGetValue(index, out int mappedIndex))
            {
                newTriangles.Add(mappedIndex);
            }
            else
            {
                Debug.LogWarning($"无法映射顶点索引: {index}");
                newTriangles.Add(0); // 默认映射到第一个顶点
            }
        }

        // 更新数据
        data.Vertices = newVertices.ToArray();
        data.Normals = newNormals.ToArray();
        data.UVs = newUVs.ToArray();
        data.UV2s = newUV2s.ToArray();
        data.Colors = newColors.ToArray();
        data.Triangles = newTriangles.ToArray();

        Debug.Log($"顶点索引重映射完成: 原始最小索引={minIndex}, 新最小索引=0, 顶点数量从{data.Vertices.Length}减少到{newVertices.Count}");
    }

     

    // 解析颜色数据的辅助方法
    private bool TryParseColor(string[] values, string[] headers, string columnPrefix, out Color result)
    {
        result = Color.white;

        if (string.IsNullOrEmpty(columnPrefix) || columnPrefix == "None")
        {
            return false; // 如果设置为不读取，直接返回
        }

        for (int i = 0; i < headers.Length; i++)
        {
            string header = headers[i].Trim();
            if (header.StartsWith(columnPrefix + ".r"))
            {
                if (i + 3 < values.Length &&
                    float.TryParse(values[i].Trim(), out float r) &&
                    float.TryParse(values[i + 1].Trim(), out float g) &&
                    float.TryParse(values[i + 2].Trim(), out float b) &&
                    float.TryParse(values[i + 3].Trim(), out float a))
                {
                    // 确保颜色值在0-1范围内
                    r = Mathf.Clamp01(r);
                    g = Mathf.Clamp01(g);
                    b = Mathf.Clamp01(b);
                    a = Mathf.Clamp01(a);

                    result = new Color(r, g, b, a);
                    return true;
                }
                else if (i + 2 < values.Length &&
                    float.TryParse(values[i].Trim(), out r) &&
                    float.TryParse(values[i + 1].Trim(), out g) &&
                    float.TryParse(values[i + 2].Trim(), out b))
                {
                    // 没有Alpha通道时，默认设为1
                    r = Mathf.Clamp01(r);
                    g = Mathf.Clamp01(g);
                    b = Mathf.Clamp01(b);

                    result = new Color(r, g, b, 1.0f);
                    return true;
                }
                else
                {
                    // 记录解析失败的位置
                    Debug.LogWarning($"解析Color失败: 列 {header}, 行数据不足或格式错误");
                    return false;
                }
            }
        }

        Debug.LogWarning($"解析Color失败: 未找到匹配的列前缀 {columnPrefix}");
        return false;
    }

    // 验证RDM数据的完整性
    private bool ValidateRDMData(RDMData data, AssetImportContext ctx)
    {
        bool isValid = true;

        // 检查顶点数量
        if (data.Vertices.Length == 0)
        {
            ctx.LogImportError("RDM数据验证失败：顶点数量为0");
            isValid = false;
        }

        // 检查法线数量
        if (data.Normals.Length > 0 && data.Normals.Length != data.Vertices.Length)
        {
            ctx.LogImportError($"RDM数据验证失败：法线数量({data.Normals.Length})与顶点数量({data.Vertices.Length})不匹配");
            isValid = false;
        }

        // 检查UV数量
        if (data.UVs.Length > 0 && data.UVs.Length != data.Vertices.Length)
        {
            ctx.LogImportError($"RDM数据验证失败：UV数量({data.UVs.Length})与顶点数量({data.Vertices.Length})不匹配");
            isValid = false;
        }

        // 检查UV2数量
        if (data.UV2s.Length > 0 && data.UV2s.Length != data.Vertices.Length)
        {
            ctx.LogImportError($"RDM数据验证失败：UV2数量({data.UV2s.Length})与顶点数量({data.Vertices.Length})不匹配");
            isValid = false;
        }

        // 检查颜色数量
        if (data.Colors.Length > 0 && data.Colors.Length != data.Vertices.Length)
        {
            ctx.LogImportError($"RDM数据验证失败：颜色数量({data.Colors.Length})与顶点数量({data.Vertices.Length})不匹配");
            isValid = false;
        }

        // 检查三角形索引
        if (data.Triangles.Length % 3 != 0)
        {
            ctx.LogImportError($"RDM数据验证失败：三角形索引数量({data.Triangles.Length})不是3的倍数");
            isValid = false;
        }

        foreach (int index in data.Triangles)
        {
            if (index >= data.Vertices.Length)
            {
                ctx.LogImportError($"RDM数据验证失败：三角形索引({index})超出顶点数组范围({data.Vertices.Length})");
                isValid = false;
                break;
            }
        }

        return isValid;
    }

    private Mesh CreateMeshFromRDMData(RDMData data, RDMImportSettings settings)
    {
        try
        {
            Mesh mesh = new Mesh();
            mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
            // 设置顶点
            mesh.vertices = data.Vertices;
            Debug.Log($"设置顶点: {data.Vertices.Length} 个");

            // 设置三角形
            mesh.triangles = data.Triangles;
            Debug.Log($"设置三角形: {data.Triangles.Length / 3} 个");

            // 新增：如果法线列为空，自动重计算法线
            if (string.IsNullOrEmpty(settings.normalColumn) || settings.normalColumn == "None" || settings.calculateSmoothNormals)
            {
                mesh.RecalculateNormals();
                Debug.Log("法线列名为空，已自动重计算法线");
            }
            else if (data.Normals.Length > 0 && data.Normals.Length == data.Vertices.Length)
            {
                mesh.normals = data.Normals;
                Debug.Log("已设置法线数据");
            }
            else if (settings.calculateNormals)
            {
                mesh.RecalculateNormals();
                Debug.Log("已自动计算法线");
            }
            else
            {
                Debug.LogWarning("未设置法线数据且未启用自动计算法线选项");
            }

            // 自动生成切线
            if (settings.generateTangents)
            {
                mesh.RecalculateTangents();
                Debug.Log("已自动生成切线");
            }

            // 设置UV
            if (data.UVs.Length > 0 && data.UVs.Length == data.Vertices.Length)
            {
                mesh.uv = data.UVs;
                Debug.Log("已设置UV数据");
            }
            else
            {
                Debug.LogWarning("未设置UV数据");
            }

            // 设置UV2
            if (data.UV2s.Length > 0 && data.UV2s.Length == data.Vertices.Length &&
                !string.IsNullOrEmpty(settings.uv2Column) && settings.uv2Column != "None")
            {
                mesh.uv2 = data.UV2s;
                Debug.Log("已设置UV2数据");
            }
            else if (!string.IsNullOrEmpty(settings.uv2Column) && settings.uv2Column != "None")
            {
                Debug.LogWarning("UV2数据不完整或格式错误，已跳过设置");
            }

            // 设置顶点颜色
            if (data.Colors.Length > 0 && data.Colors.Length == data.Vertices.Length &&
                !string.IsNullOrEmpty(settings.colorColumn) && settings.colorColumn != "None")
            {
                mesh.colors = data.Colors;
                Debug.Log("已设置顶点颜色数据");
            }
            else if (!string.IsNullOrEmpty(settings.colorColumn) && settings.colorColumn != "None")
            {
                Debug.LogWarning("颜色数据不完整或格式错误，已跳过设置");
            }

            // 优化网格
            mesh.Optimize();
            mesh.RecalculateBounds();

            return mesh;
        }
        catch (Exception ex)
        {
            Debug.LogError($"创建 Mesh 时出错\n错误: {ex.Message}\n{ex.StackTrace}");
            return null;
        }
    }

    // 反转顶点索引顺序（修正版）
    private void ReverseVertexIndices(Mesh mesh)
    {
        int[] triangles = mesh.triangles;

        for (int i = 0; i < triangles.Length; i += 3)
        {
            // 交换每个三角形的第二个和第三个顶点索引
            int temp = triangles[i + 1];
            triangles[i + 1] = triangles[i + 2];
            triangles[i + 2] = temp;
        }

        mesh.triangles = triangles;
        Debug.Log("已反转顶点索引顺序");
    }

    // 翻转UV的Y轴
    private void FlipUVY(Vector2[] uvs)
    {
        for (int i = 0; i < uvs.Length; i++)
        {
            uvs[i] = new Vector2(uvs[i].x, 1.0f - uvs[i].y);
        }
    }

    // 反转法线方向
    private void InvertNormals(Vector3[] normals)
    {
        for (int i = 0; i < normals.Length; i++)
        {
            normals[i] = -normals[i];
        }
    }

    // 反转三角形顶点顺序
    private void ReverseWindingOrder(int[] triangles)
    {
        for (int i = 0; i < triangles.Length; i += 3)
        {
            // 交换第二个和第三个顶点索引
            int temp = triangles[i + 1];
            triangles[i + 1] = triangles[i + 2];
            triangles[i + 2] = temp;
        }
    }

    // 计算平滑法线
    private void CalculateSmoothNormals(Mesh mesh, float angleThresholdDegrees)
    {
        Vector3[] vertices = mesh.vertices;
        int[] triangles = mesh.triangles;
        int vertexCount = vertices.Length;
        int triangleCount = triangles.Length / 3;

        // 预先计算每个三角形的法线
        Vector3[] triangleNormals = new Vector3[triangleCount];
        for (int i = 0; i < triangleCount; i++)
        {
            int index = i * 3;
            int v1 = triangles[index];
            int v2 = triangles[index + 1];
            int v3 = triangles[index + 2];

            Vector3 edge1 = vertices[v2] - vertices[v1];
            Vector3 edge2 = vertices[v3] - vertices[v1];
            triangleNormals[i] = Vector3.Cross(edge1, edge2).normalized;
        }

        // 建立顶点到三角形的映射关系
        Dictionary<int, List<int>> vertexToTriangles = new Dictionary<int, List<int>>();
        for (int i = 0; i < triangleCount; i++)
        {
            int index = i * 3;
            int v1 = triangles[index];
            int v2 = triangles[index + 1];
            int v3 = triangles[index + 2];

            if (!vertexToTriangles.ContainsKey(v1))
                vertexToTriangles[v1] = new List<int>();
            if (!vertexToTriangles.ContainsKey(v2))
                vertexToTriangles[v2] = new List<int>();
            if (!vertexToTriangles.ContainsKey(v3))
                vertexToTriangles[v3] = new List<int>();

            vertexToTriangles[v1].Add(i);
            vertexToTriangles[v2].Add(i);
            vertexToTriangles[v3].Add(i);
        }

        // 计算每个顶点的平滑法线
        Vector3[] smoothNormals = new Vector3[vertexCount];
        float angleThreshold = Mathf.Cos(angleThresholdDegrees * Mathf.Deg2Rad);

        for (int vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++)
        {
            if (!vertexToTriangles.TryGetValue(vertexIndex, out List<int> adjacentTriangles))
            {
                // 如果顶点没有相邻三角形，使用默认法线
                smoothNormals[vertexIndex] = Vector3.up;
                continue;
            }

            Vector3 averageNormal = Vector3.zero;

            // 当前顶点位置
            Vector3 vertexPos = vertices[vertexIndex];

            foreach (int triangleIndex in adjacentTriangles)
            {
                // 获取当前三角形的法线
                Vector3 triangleNormal = triangleNormals[triangleIndex];

                // 计算权重（可选：基于三角形面积或其他因素）
                float weight = 1.0f;

                // 累加法线
                averageNormal += triangleNormal * weight;
            }

            // 归一化法线
            if (averageNormal != Vector3.zero)
            {
                smoothNormals[vertexIndex] = averageNormal.normalized;
            }
            else
            {
                smoothNormals[vertexIndex] = Vector3.up;
            }
        }

        // 应用平滑法线
        mesh.normals = smoothNormals;
    }

    // 辅助方法：解析Vector3
    private bool TryParseVector3(string[] values, string[] headers, string columnPrefix, out Vector3 result)
    {
        result = Vector3.zero;

        for (int i = 0; i < headers.Length; i++)
        {
            string header = headers[i].Trim();
            if (header.StartsWith(columnPrefix + ".x"))
            {
                if (i + 2 < values.Length &&
                    float.TryParse(values[i].Trim(), out float x) &&
                    float.TryParse(values[i + 1].Trim(), out float y) &&
                    float.TryParse(values[i + 2].Trim(), out float z))
                {
                    result = new Vector3(x, y, z);
                    return true;
                }
                else
                {
                    // 记录解析失败的位置
                    Debug.LogWarning($"解析Vector3失败: 列 {header}, 行数据不足或格式错误");
                    return false;
                }
            }
        }

        Debug.LogWarning($"解析Vector3失败: 未找到匹配的列前缀 {columnPrefix}");
        return false;
    }

    // 辅助方法：解析Vector2
    private bool TryParseVector2(string[] values, string[] headers, string columnPrefix, out Vector2 result)
    {
        result = Vector2.zero;

        for (int i = 0; i < headers.Length; i++)
        {
            string header = headers[i].Trim();
            if (header.StartsWith(columnPrefix + ".x"))
            {
                if (i + 1 < values.Length &&
                    float.TryParse(values[i].Trim(), out float x) &&
                    float.TryParse(values[i + 1].Trim(), out float y))
                {
                    result = new Vector2(x, y);
                     
                    return true;
                }
                else
                {
                    // 记录解析失败的位置
                    Debug.LogWarning($"解析Vector2失败: 列 {header}, 行数据不足或格式错误");
                    return false;
                }
            }
        }

        Debug.LogWarning($"解析Vector2失败: 未找到匹配的列前缀 {columnPrefix}");
        return false;
    }

    // RDM 数据容器类
    private class RDMData
    {
        public Vector3[] Vertices;
        public Vector3[] Normals;
        public Vector2[] UVs;
        public Vector2[] UV2s;
        public Color[] Colors;
        public int[] Triangles;
        public int[] RawIndices; // 新增：存储原始索引
    }
}

// 自定义Inspector面板
[CustomEditor(typeof(RDMAssetImporter))]
public class RDMAssetImporterEditor : ScriptedImporterEditor
{
    private SerializedProperty importSettingsProp;
    private SerializedProperty positionColumnProp;
    private SerializedProperty normalColumnProp;
    private SerializedProperty uvColumnProp;
    private SerializedProperty colorColumnProp;
    private SerializedProperty uv2ColumnProp;
    private SerializedProperty generateTangentsProp;
    private SerializedProperty calculateNormalsProp;
    private SerializedProperty flipUVYProp;
    private SerializedProperty invertNormalsProp;
    private SerializedProperty reverseWindingProp;
    private SerializedProperty reverseVertexIndicesProp;
    private SerializedProperty calculateSmoothNormalsProp;
    private SerializedProperty smoothAngleThresholdProp;
    private SerializedProperty autoRemapIndicesProp; // 新增：自动重映射索引选项

    private bool settingsExpanded = true;

    public override void OnEnable()
    {
        base.OnEnable();

        importSettingsProp = serializedObject.FindProperty("importSettings");
        if (importSettingsProp != null)
        {
            positionColumnProp = importSettingsProp.FindPropertyRelative("positionColumn");
            normalColumnProp = importSettingsProp.FindPropertyRelative("normalColumn");
            uvColumnProp = importSettingsProp.FindPropertyRelative("uvColumn");
            colorColumnProp = importSettingsProp.FindPropertyRelative("colorColumn");
            uv2ColumnProp = importSettingsProp.FindPropertyRelative("uv2Column");
            generateTangentsProp = importSettingsProp.FindPropertyRelative("generateTangents");
            calculateNormalsProp = importSettingsProp.FindPropertyRelative("calculateNormals");
            flipUVYProp = importSettingsProp.FindPropertyRelative("flipUVY");
            invertNormalsProp = importSettingsProp.FindPropertyRelative("invertNormals");
            reverseWindingProp = importSettingsProp.FindPropertyRelative("reverseWinding");
            reverseVertexIndicesProp = importSettingsProp.FindPropertyRelative("reverseVertexIndices");
            calculateSmoothNormalsProp = importSettingsProp.FindPropertyRelative("calculateSmoothNormals");
            smoothAngleThresholdProp = importSettingsProp.FindPropertyRelative("smoothAngleThreshold");
            autoRemapIndicesProp = importSettingsProp.FindPropertyRelative("autoRemapIndices"); // 新增
        }
    }
    static string[] inputList = { "_input3", "_input4", "_input5", "_input6", "_input7", "_input8" };
    static string[] inputList2 = { "None","_input3", "_input4", "_input5", "_input6", "_input7", "_input8" };
    public override void OnInspectorGUI()
    {
        var importer = target as RDMAssetImporter;
        string filePath = importer.assetPath;

        serializedObject.Update();

        if (importSettingsProp != null)
        {
            EditorGUILayout.Space();
            settingsExpanded = EditorGUILayout.Foldout(settingsExpanded, "RDM Import Settings", true);

            if (settingsExpanded)
            {
                EditorGUI.indentLevel++;

                EditorGUILayout.PropertyField(positionColumnProp, new GUIContent("Position Column"));
                EditorGUILayout.PropertyField(normalColumnProp, new GUIContent("Normal Column"));

                // UV列设置
                EditorGUILayout.PropertyField(uvColumnProp, new GUIContent("UV Column"));
                EditorGUILayout.BeginHorizontal();

                foreach (var v in inputList)
                {
                    if (GUILayout.Button(v, GUILayout.Width(60)))
                        uvColumnProp.stringValue = v;
                }
                 
                EditorGUILayout.EndHorizontal();

                // 颜色列设置
                EditorGUILayout.PropertyField(colorColumnProp, new GUIContent("Color Column"));
                EditorGUILayout.BeginHorizontal();


                foreach (var v in inputList2)
                {
                    if (GUILayout.Button(v, GUILayout.Width(60)))
                        colorColumnProp.stringValue = v;
                }
                
                EditorGUILayout.EndHorizontal();

                // UV2列设置
                EditorGUILayout.PropertyField(uv2ColumnProp, new GUIContent("UV2 Column"));
                EditorGUILayout.BeginHorizontal();

                foreach (var v in inputList2)
                {
                    if (GUILayout.Button(v, GUILayout.Width(60)))
                        uv2ColumnProp.stringValue = v;
                }
                 
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.PropertyField(generateTangentsProp, new GUIContent("Generate Tangents"));
                EditorGUILayout.PropertyField(calculateNormalsProp, new GUIContent("Calculate Normals"));
                EditorGUILayout.PropertyField(flipUVYProp, new GUIContent("Flip UV Y"));
                EditorGUILayout.PropertyField(invertNormalsProp, new GUIContent("Invert Normals"));
                EditorGUILayout.PropertyField(reverseWindingProp, new GUIContent("Reverse Winding"));
                EditorGUILayout.PropertyField(reverseVertexIndicesProp, new GUIContent("Reverse Vertex Indices"));

                // 新增：自动重映射索引选项
                EditorGUILayout.PropertyField(autoRemapIndicesProp, new GUIContent("Auto Remap Indices"));

                // 平滑法线设置
                EditorGUILayout.PropertyField(calculateSmoothNormalsProp, new GUIContent("Calculate Smooth Normals"));
                if (calculateSmoothNormalsProp.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(smoothAngleThresholdProp, new GUIContent("Smooth Angle Threshold (degrees)"));
                    EditorGUI.indentLevel--;
                }

                EditorGUI.indentLevel--;
            }
        }

        EditorGUILayout.Space();
        ApplyRevertGUI();
    }

    protected override void Apply()
    {
        // 在应用设置前确保数据已更新
        serializedObject.ApplyModifiedProperties();

        // 显示保存成功的提示
        EditorUtility.DisplayDialog("RDM Import Settings", "Settings saved successfully!", "OK");

        base.Apply();
    }
}